#/usr/bin/perl

package NNexus;

use strict;

use Encode qw{is_utf8};
use Time::HiRes qw ( time alarm sleep );
use LWP::Simple;

use NNexus::Classification;
use NNexus::Concepts;
use NNexus::DB;

use vars qw( $config );

#
# Get the domainid from config hash.
#
sub getdomainid {
	my $domain = shift;
	
	return $config->{'domains'}->{'domain'}->{$domain}->{'domainid'};
}

# get the domain specific blacklist
sub getdomainblacklist {
	my $domain = shift;

	my $url = $config->{'domains'}->{'domain'}->{$domain}->{'link'};
	my $content = get("$url");
	if ( defined $content ) {
		my $ref = XMLin($content);
		my @bl = split( /\s*,\s*/, $ref->{'blacklist'} );
		foreach my $b ( @bl ) {
			$b = lc($b);
		}
		return \@bl;

	} else {
		print "using default blacklist\n";
	}
}

#get the domain priorities as an arrayref of domain ids
sub getdomainpriorities {
	my $domain = shift;

	my @priorities = ();
	
	my $url = $config->{'domains'}->{'domain'}->{$domain}->{'link'};
	my $content = get("$url");
	if ( defined $content ) {
		my $ref = XMLin($content);
		my @prio = split( /\s*,\s*/, $ref->{'priority'} );
		foreach my $p (@prio){
			push @priorities, getdomainidfromdb($p);
		}
		return \@priorities;

	} else {
		print "using default priorities\n";
	}
}

#
# Get the domainid from the DB.
# Note: this should only be called to determine the id of a new domain from
#  the Config.pm file
#
sub getdomainidfromdb {
	my $domain = shift;
	
	#we no longer use the db we just use the config hash
	
	my $sth =cachedPrepare( "select domainid FROM domain WHERE name = ?");
	$sth->execute( $domain );
	my $domid;
    $sth->bind_columns(\$domid);
    $sth->fetch();
    $sth->finish();

	return $domid;
}



#
# Get the domainname from the DB.
#

#CACHE this stuff.
my %domaincache = ();
sub getdomainhash {
	my $domid = shift;
	
	if ( ! exists $domaincache{$domid} ) {
		my $sth = cachedPrepare( "select * from domain where domainid = ?" );
		$sth->execute( $domid );
		$domaincache{$domid} = $sth->fetchrow_hashref();
	}

	return $domaincache{$domid};
}




1;
